import { time } from "console";
import { ILogin } from "../common/defInterface";
import lyu from "../framework/lyu";
import gMongo from "../storage/gMongo";
import gRedis from "../storage/gRedis";
import Fn from "../framework/common/Fn";

export default class loginWeb {
    static async start() {
        lyu.webOn("OnLogin", async (data, ctx) => {
            let account = data.account;
            let password = data.password;
            let channel = data.channel ?? 0;
            let ip = ctx.ip.substring(7) ?? "";
            let userData: ILogin = await gRedis.getUserAccountData(account);

            let curDate = new Date();
            if (userData == null) {
                userData = await gMongo.getUserData(account);
                if (userData == null) {
                    let accountId = await gRedis.getUserAccountSeedId();
                    userData = {
                        accountId: accountId,
                        account: account,
                        password: password,
                        channel: channel,
                        state: 0,
                        createTime: curDate,
                        createIp: ip,
                        lastLoginTime: curDate,
                        lastLoginIp: ip,
                    };
                    await gMongo.setUserData(userData);
                    await gRedis.setUserAccountData(account, userData);
                }
            }
            if (userData.password == password) {
                // 密码正确登录成功
                // 生成token
                let date = Fn.getCurDate(curDate);
                gMongo.setLoginLog({
                    account: account,
                    time: date.format("YYYY-MM-DD HH:mm:ss"),
                    ip: ip,
                });
                return "登录成功"
            } else {
                return {
                    errCode: 10001,
                }
            }
        })
    }
}